import { defineStore } from 'pinia'
import { login as loginApi, getUserInfo as getUserInfoApi } from '@/api/auth'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('admin_token') || '',
    userInfo: JSON.parse(localStorage.getItem('admin_userInfo') || '{}')
  }),
  
  actions: {
    // 登录
    async login(credentials) {
      const res = await loginApi(credentials)
      this.token = res.data.token
      this.userInfo = {
        userId: res.data.userId,
        username: res.data.username,
        roles: res.data.roles
      }
      
      localStorage.setItem('admin_token', this.token)
      localStorage.setItem('admin_userInfo', JSON.stringify(this.userInfo))
    },
    
    // 获取用户信息
    async getUserInfo() {
      const res = await getUserInfoApi()
      this.userInfo = res.data
      localStorage.setItem('admin_userInfo', JSON.stringify(this.userInfo))
    },
    
    // 退出登录
    logout() {
      this.token = ''
      this.userInfo = {}
      localStorage.removeItem('admin_token')
      localStorage.removeItem('admin_userInfo')
    }
  }
})

